package com.agilya.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.agilya.dao.DAOQCM;
import com.agilya.dao.daointerface.QCMDAO;
import com.agilya.modele.QCM;

/**
 * Servlet implementation class AfficherQCM
 * 
 * Afficher la liste des QCM
 * 
 */
@WebServlet("/AfficherQCM")
public class AfficherQCM extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Inject
	@DAOQCM
	private QCMDAO qcmdao;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AfficherQCM() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// cas d'affichage des QCM liés à un chapitre
		String idChapitrestr = request.getParameter("idChapitre");

		if (idChapitrestr != null) {
			int idChapitre = Integer.parseInt(idChapitrestr);
			RequestDispatcher rd;

			List<QCM> qcm = new ArrayList<>();

			try {
				qcm = qcmdao.getAllQCMbyChapitre(idChapitre);
				request.setAttribute("listeQCM", qcm);

			} catch (Exception e) {
				request.setAttribute("erreurPage", "Une erreur est survenue, veuillez recommencer plus tard");
				e.printStackTrace();
			}

			request.setAttribute("page", "/afficherQCM.jsp");
			rd = request.getRequestDispatcher("/page.jsp");
			rd.forward(request, response);

		} else {
			doPost(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// cas d'affichage de tous les QCM

		RequestDispatcher rd;
		List<QCM> qcm = new ArrayList<>();

		try {
			qcm = qcmdao.getAllQCM();
			request.setAttribute("listeQCM", qcm);

		} catch (Exception e) {
			request.setAttribute("erreurPage", "Une erreur est survenue, veuillez recommencer plus tard");
			e.printStackTrace();
		}
		request.setAttribute("page", "/afficherQCM.jsp");
		rd = request.getRequestDispatcher("/page.jsp");
		rd.forward(request, response);
	}

}
